<?php
/**
 * 
 * @author Paolo Bertuzzo
 *
 */
namespace Catalog\Controller;

use Utilities\Geolocation\GeolocationService;
use Zend\Mvc\MvcEvent;
use Catalog\Service\StoreService;
use Catalog\Entity\Store;
use Utilities\Session\SessionFacade;
use Zend\Mvc\Controller\AbstractActionController;

class AbstractGeolocalizedController extends AbstractActionController
{
    
    /**
     */
    private $geolocationService;

    /**
     */
    private $storeService;
    
    /**
     * 
     * @param GeolocationService $geolocationService
     * @param StoreService $storeService
     */
    public function __construct(GeolocationService $geolocationService, StoreService $storeService) 
    {
        $this->storeService = $storeService;
    	$this->geolocationService = $geolocationService;
    }
    
    /**
     * (non-PHPdoc)
     * @see \Zend\Mvc\Controller\AbstractActionController::onDispatch()
     */
    public function onDispatch(MvcEvent $e)
    {
        $countryInPath = $this->params()->fromRoute('country');
        
        // Check if country is in URL path
        if (empty($countryInPath)) 
        {
            // If not, retrieve store from geolocation information and redirect user to the proper store
            $ip = $e->getRequest()->getServer('REMOTE_ADDR');
            $country = null;
            
            if (!empty($ip))
                $country = $this->geolocationService->getCountryCode($ip);

            // Get the store from the user country. If user comes from an unsupported country, retrieve the default store
            $store = $this->storeService->getStore($country);

            // Redirect user to the proper store
            return $this->redirect()->toRoute('catalog', array('country' => $store->getCountry()));
        } else {
            $store = $this->storeService->getStore($countryInPath);
            
            if ($store->getCountry() != $countryInPath)
                return $this->redirect()->toRoute('catalog', array('country' => $store->getCountry()));
                            
            // If controls went fine, save store in session for later use
            $this->saveStoreInSession($store);
        }
        
        parent::onDispatch($e);
    }
    
    /**
     */
    private function saveStoreInSession($store) 
    {
    	$sessionFacade = new SessionFacade();
    	
    	$sessionFacade->setStore($store);
    	$sessionFacade->setLocale(sprintf('%s_%s', $store->getLanguage(), $store->getCountry()));
    }
    
    /**
     */
    public function getStore() 
    {
        $sessionFacade = new SessionFacade();
         
        return $sessionFacade->getStore();
    }

}

?>